package com.tianwen.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianwen.management.entity.Department;
import com.tianwen.management.entity.Employee;
import com.tianwen.management.service.DepartmentService;
import com.tianwen.management.mapper.DepartmentMapper;
import com.tianwen.management.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
* @author Administrator
* @description 针对表【department(部门表)】的数据库操作Service实现
* @createDate 2023-05-12 15:34:16
*/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department>
    implements DepartmentService{
@Resource
private DepartmentMapper departmentMapper;
@Autowired
private EmployeeService employeeService;
    @Override
    public List<Department> page(Integer page, Integer pageSize, String name) {
        QueryWrapper<Department> queryWrapper=new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(name)){
             queryWrapper.like("name",name);
        }
          queryWrapper.orderByDesc("id");
        Page<Department> pageInfo=new Page<>(page,pageSize);
        Page<Department> departmentPage = departmentMapper.selectPage(pageInfo, queryWrapper);
        return departmentPage.getRecords();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeAndEmpName(Long id) {
        QueryWrapper<Employee> queryWrap=new QueryWrapper<>();
        queryWrap.eq("dept_id",id);
        List<Employee> employees = employeeService.list(queryWrap);
        employees.stream().forEach(item->{
            item.setDeptId(null);
        });
        employeeService.saveOrUpdateBatch(employees);
        departmentMapper.deleteById(id);
        return true;
    }

    @Override
    @Transactional
    public Boolean updateAndEmpName(Department department) {
        departmentMapper.updateById(department);
        QueryWrapper<Employee> queryWrap=new QueryWrapper<>();
        queryWrap.eq("dept_id",department.getId());
        List<Employee> employees = employeeService.list(queryWrap);
        employees.stream().forEach(item->{
            item.setDeptName(department.getName());
        });
        return true;
    }
}




